﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Grids;
using VAdvantage.Classes;
using VAdvantage.Model;
using VAdvantage.DataBase;
using System.Windows.Data;

namespace VAdvantage.Controls
{
    public partial class VAccount : UserControl,IControl,IEditingControl
    {

        #region "Declaration"

        private MAccountLookup _mAccount;
        private Object _value;
        private String _title;
        private int _windowNo;
        private bool _mandatory;
        private bool _readOnly;

        private bool _focus;
        private String _columnName;
        /**	Logger			*/
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VPAttribute).FullName);
        private GridField _field = null;

        private int _displayType = DisplayType.Account;

        private ToolTip tpDesc = new ToolTip();


        #endregion

        #region Properties
        /// <summary>
        /// Text of Control
        /// </summary>
        public string Text
        {
            get { return this.txtAccount.Text; }
            set { this.txtAccount.Text = value; }
        }
        #endregion

        #region Property

        public static readonly DependencyProperty TextValueProperty =
         DependencyProperty.Register("TextValue", typeof(int), typeof(VAdvantage.Controls.VAccount), new PropertyMetadata((o, e) =>
         {
             ((VAccount)o).SetTextValue((int)e.NewValue);

         }));


        public int TextValue
        {
            get
            {
                return ((int)GetValue(VAccount.TextValueProperty));
            }
            set
            {
                SetValue(VAccount.TextValueProperty, value);
            }
        }

        void SetTextValue(int newVal)
        {
            //TextValue = newVal;
            int? id = null;
            if (TextValue == 0)
            {
                id = null;
            }
            else
            {
                id = TextValue;
            }
            SetValue(id);
        }


        #endregion


        public VAccount()   
        {
            InitializeComponent();
            btnAccount.Content = new Image() { Source = Utility.Envs.LoadImageSource("Account10.png") };
            //<Image Source="Images\Account10.png"></Image>
        }

        public VAccount(String columnName, bool mandatory, bool isReadOnly, bool isUpdateable,
        MAccountLookup mAccount, String title): this()
        {
            
            //this.Name = columnName;
            _columnName = columnName;
            _mAccount = mAccount;
            _title = title;

            if (isReadOnly || !isUpdateable)
                SetReadOnly(true);
            else
                SetReadOnly(false);
            SetIsMandatory(mandatory);


            //if (!DataBase.GlobalVariable.IsVisualEditor)
            //{
                this.btnAccount.Click +=new RoutedEventHandler(btnAccount_Click);
                this.txtAccount.TextChanged += new TextChangedEventHandler(txtAccount_TextChanged);
                this.txtAccount.IsReadOnly = true;
            //}
            //else
            //{
            //    this.txtAccount.MouseDown += new MouseEventHandler(txtAccount_MouseDown);
            //    this.txtAccount.MouseMove += new MouseEventHandler(txtAccount_MouseMove);
            //    this.txtAccount.MouseUp += new MouseEventHandler(txtAccount_MouseUp);
            //    this.txtAccount.MouseEnter += new EventHandler(txtAccount_MouseEnter);
            //}

            //this.Width = 300;
           // this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;
        }

        void txtAccount_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetColor();
        }

        private void btnAccount_Click(object sender, RoutedEventArgs e)
        {
            Cmd_Button();
        }

        /// <summary>
        /// Command Button
        /// </summary>
        private void Cmd_Button()
        {
            //this.ParentForm.Cursor = Cursors.WaitCursor;
            //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            int C_AcctSchema_ID = Utility.Envs.GetCtx().GetContextAsInt(_windowNo, "C_AcctSchema_ID");
            Dialogs.VAccountDialog ad = new Dialogs.VAccountDialog(_title,
                _mAccount, C_AcctSchema_ID);
            //this.ParentForm.Cursor = Cursors.Default;
            //setCursor(Cursor.getDefaultCursor());
            //

            ad.Closed += (s, e) =>
                {
                    int? newValue = ad.GetValue();
                    if (newValue == null)
                        return;

                    //ADD IN AccountList SL 
                    Model.MLookupStore.AccountCache[newValue.Value] = new ValueNamePair(ad.GetCombination(), ad.GetCombination());
                    //End
                    if (EditingControlDataGridView != null)
                    {
                        SetValueInDataGridColumn(newValue);
                        EditingControlDataGridView.RaiseCellValueChanged(this);
                        _field.SetValue(newValue);
                        ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), newValue);
                    }
                    else
                    {

                        SetValue(newValue);	//	set explicitly
                        _focus = true;
                        if (VetoableChangeListener != null)
                        {
                            VetoableChangeListener(this, EventArgs.Empty);
                        }
                        _focus = false;
                    }
                };
        }


        #region

        public event EventHandler VetoableChangeListener;
        private Binding binding;
        

        public int GetDisplayType()
        {
            return DisplayType.Account;
        }

        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            this.txtAccount.IsReadOnly = readOnly;
            this.txtAccount.IsTabStop = !readOnly;
            if (readOnly)
            {
               // this.txtAccount.Width = this.Width;
                btnAccount.Visibility = System.Windows.Visibility.Collapsed;

               
            }
            else
            {
                //this.txtAccount.Width = this.Width - btnAccount.Width;
                btnAccount.Visibility = System.Windows.Visibility.Visible;
            }

            SetBackGround(readOnly);
        }


        private SolidColorBrush backColorBrush = new SolidColorBrush();

       

        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.txtAccount.Background = backColorBrush;
            }
            else
            {
                backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtAccount.Background = backColorBrush;
                SetColor();
            }
        }

        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.Text == "")
                {
                    backColorBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.txtAccount.Background = backColorBrush;
                }
                else
                {
                    backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    this.txtAccount.Background = backColorBrush;
                    if (_field != null)
                        _field.SetError(false);
                }
            }
        }






        /// <summary>
        /// Set Back color to mandatory color 
        /// </summary>
        

        public GridField GetField()
        {
            return _field;
        }

        public void SetField(GridField mField)
        {
            if (mField != null)
                _windowNo = mField.GetWindowNo();
            _field = mField;
        }

        public string GetName()
        {
            return _columnName;
        }

        public void SetName(string name)
        {
            _columnName = name;
        }

        public string GetText()
        {
            return txtAccount.Text;
        }

        public object GetValue()
        {
            return this._value;
        }

        public void SetValue(object value)
        {
            _value = value;
            if (value == null || value == DBNull.Value)
            {
                txtAccount.Text = "";
            }
            else
            {
                // txtAccount.Text = _mAccount.GetDisplayFromList(value);	//	loads value
                   tpDesc.Content = _mAccount.GetDescription();
                //}


                string desc = _mAccount.GetDisplayFromList(value); 

                if (desc != null && (desc == "" || desc.StartsWith("{")))
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        desc = _mAccount.GetDisplay(value);
                        Dispatcher.BeginInvoke(() => txtAccount.Text = desc);
                    });
                }
                else
                {
                    txtAccount.Text = desc;
                }
            }


            SetColor();
            //tpDesc.SetToolTip(txtAccount, _mAccount.GetDescription());
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

       

        public string GetSelectedText()
        {
            return txtAccount.SelectedText;
            //throw new NotImplementedException();
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false; // throw new NotImplementedException();
            }
            set
            {
                //throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return  this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus; }
        }

        public string BindValue
        {
            set
            {
                //this.txtValue.Text = "-11";
                binding = null;
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;

                this.SetBinding(VAccount.TextValueProperty, binding);

                //this.txtValue.Text = "-11";
            }
        }

        public void Dispose()
        {
            _mAccount = null;
            _field = null;
            //throw new NotImplementedException();
        }
        #endregion

        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }
    }
}
